Implementing Unit Tests | Doctest
Doctest Module is used to write tests in the form of interactive Python sessions within docstrings and then automatically run those tests to verify that the code behaves as expected. Doctest Module finds patterns in the docstring that looks like interactive shell commands.
Now, we will create a file named as main.py and we will create a test code using docstring.
main.py
def add(a, b):
"""
Function to add two numbers.
>>> add(2, 3)
5
>>> add(-1, 1)
0
"""
return a + b
def subtract(a, b):
"""
Function to subtract two numbers.
>>> subtract(5, 2)
3
>>> subtract(10, 5)
4
"""
return a - b
To run the program, write the following command in your terminal in the same directory as main.py file.
python -m doctest main.py
Output:
Getting Started With Unit Testing in Python
In Python, unit tests are the segments of codes that are written to test other modules and files that we refer to as a unit. Python Unit Testing is a very important part of the software development process that helps us to ensure that the code works properly without any errors. In this article, we will learn about Python Testing with the help of examples and proper explanations.
Table of Content
- What is Python Unit Testing?
- The Assert Statement
- Implementing Unit Tests | Unittest
- Implementing Unit Tests | Pytest
- Implementing Unit Tests | Nose
- Implementing Unit Tests | Doctest
- How to Write Assertions in Python Testing
- More Advanced Testing Scenarios
- Automating the Execution of Tests